package controllers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"library/models"
)

var DB *gorm.DB

// 获取所有图书，显示在列表页
func GetBooks(c *gin.Context) {
	var books []models.Book
	DB.Preload("Category").Find(&books)
	c.HTML(http.StatusOK, "book_list.html", gin.H{"Books": books})
}

// 显示添加图书页面
func ShowAddBookPage(c *gin.Context) {
	var categories []models.Category
	DB.Find(&categories)
	c.HTML(http.StatusOK, "book_add.html", gin.H{"Categories": categories})
}

// 添加图书表单提交
func AddBook(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	publisher := c.PostForm("publisher")

	// 处理 category_id，空字符串或0视为NULL
	var categoryID *uint64 = nil
	if cidStr := c.PostForm("category_id"); cidStr != "" {
		if cid, err := strconv.ParseUint(cidStr, 10, 64); err == nil && cid != 0 {
			categoryID = &cid
		}
	}

	publishedAtStr := c.PostForm("published_at")
	description := c.PostForm("description")
	publishedAt, _ := time.Parse("2006-01-02", publishedAtStr)

	book := models.Book{
		Title:       title,
		Author:      author,
		Publisher:   publisher,
		CategoryID:  categoryID, // 指针类型，支持NULL
		PublishedAt: publishedAt,
		Description: description,
	}
	DB.Create(&book)

	// 添加操作日志
	log := models.Log{Action: "添加图书: " + title, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/books")
}

// 显示编辑图书页面
func ShowEditBookPage(c *gin.Context) {
	id := c.Param("id")
	var book models.Book
	DB.First(&book, id)
	var categories []models.Category
	DB.Find(&categories)
	c.HTML(http.StatusOK, "book_edit.html", gin.H{"Book": book, "Categories": categories})
}

// 编辑图书表单提交
func EditBook(c *gin.Context) {
	// 优先从表单获取id，没有再从URL获取
	idStr := c.PostForm("id")
	if idStr == "" {
		idStr = c.Param("id")
	}

	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.String(http.StatusBadRequest, "无效的图书 ID")
		return
	}

	title := c.PostForm("title")
	author := c.PostForm("author")
	publisher := c.PostForm("publisher")

	// 处理 category_id，空字符串或0视为NULL
	var categoryID *uint64 = nil
	if cidStr := c.PostForm("category_id"); cidStr != "" {
		if cid, err := strconv.ParseUint(cidStr, 10, 64); err == nil && cid != 0 {
			categoryID = &cid
		}
	}

	publishedAtStr := c.PostForm("published_at")
	description := c.PostForm("description")

	publishedAt, _ := time.Parse("2006-01-02", publishedAtStr)

	var book models.Book
	if err := DB.First(&book, id).Error; err != nil {
		c.String(http.StatusNotFound, "图书不存在")
		return
	}

	// 修改字段
	book.Title = title
	book.Author = author
	book.Publisher = publisher
	book.CategoryID = categoryID // 指针类型，支持NULL
	book.PublishedAt = publishedAt
	book.Description = description

	if err := DB.Save(&book).Error; err != nil {
		c.String(http.StatusInternalServerError, "保存图书失败")
		return
	}

	log := models.Log{Action: "编辑图书: " + title, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/books")
}

// 删除图书
func DeleteBook(c *gin.Context) {
	id := c.Param("id")
	var book models.Book
	DB.First(&book, id)
	DB.Delete(&book)

	log := models.Log{Action: "删除图书: " + book.Title, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/books")
}

// 图书详情页
func BookDetail(c *gin.Context) {
	id := c.Param("id")
	var book models.Book
	DB.Preload("Category").First(&book, id)
	c.HTML(http.StatusOK, "book_detail.html", gin.H{"Book": book})
}
